package my.wudm.yummy.worker.parse;

import cn.zyzpp.util.AiPaUtil;
import my.wudm.yummy.common.model.BaseCatalogModel;
import my.wudm.yummy.common.model.BaseContentModel;
import my.wudm.yummy.common.BaseParse;
import my.wudm.yummy.common.constant.BiquConst;
import my.wudm.yummy.model.BiquCatalogModel;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.*;

public class BiquParse implements BaseParse {
    @Override
    public BaseCatalogModel parseCatalog(Document document, AiPaUtil aiPaUtil) {
        String title = document.title();
        Element body = document.body();
        BiquCatalogModel model = getCatalog(title, body);
        List<Map<String, String>> chapterList = getChapterList(body);
        model.setAllChapters(chapterList);
        return model;
    }

    private List<Map<String, String>> getChapterList(Element body) {
        List<Map<String, String>> chapterList = new ArrayList<>();
        Map<String, String> chapterMap = null;
        Elements ddElements = body.getElementsByTag("dd");
        Iterator it = ddElements.iterator();
        Element ddElm = null;
        while (it.hasNext()){
            chapterMap = new HashMap<>();
            ddElm = (Element) it.next();
            String href = ddElm.attr("href");
            String text = ddElm.text();
            chapterMap.put("href", href);
            chapterMap.put("text", text);
            chapterList.add(chapterMap);
        }
        return chapterList;
    }

    private BiquCatalogModel getCatalog(String title, Element body) {

        Element info = body.getElementById("maininfo").getElementById("info");
        String intro = body.getElementById("maininfo").getElementById("intro").text();
        String bookName = info.getElementsByTag("h1").first().text();
        Elements pElements = info.getElementsByTag("p");

        String author = pElements.get(BiquConst.AUTHOR_INDEX).text().replaceFirst("作.*者：", "");
        String lastUpdateTime = pElements.get(BiquConst.LAST_UPDATA_TIME_INDEX).text().replaceFirst("最后更新：", "");
        Element lastChapterElement = pElements.get(BiquConst.LAST_CHAPTER_INDEX).getElementsByTag("a").first();

        String href = lastChapterElement.attr("href");
        String text = lastChapterElement.text();
        Map<String, String> lastChapter = new HashMap<>();
        lastChapter.put("href", href);
        lastChapter.put("text", text);

        BiquCatalogModel model = new BiquCatalogModel();
        model.setTitle(title);
        model.setBookName(bookName);
        model.setAuthor(author);
        model.setLastUpdateTime(lastUpdateTime);
        model.setLastChapter(lastChapter);
        model.setIntro(intro);
        return model;
    }

    @Override
    public BaseContentModel parseContent(Document document, AiPaUtil aiPaUtil) {
        return null;
    }
}
